#!/usr/bin/perl -w
use strict;
use 5.010;
use autodie;


##read id => phyId maps
my $mapfile = "map.txt";
if ( ! -e $mapfile ){
  `touch $mapfile`;
}

open MAP,"<$mapfile";
my %index;  #id => phyId;
#say "Existing maps:";
while(<MAP>){
  chomp;
  my @rs = split /\s+/,$_;
  if (defined $rs[0]){
    $index{$rs[0]} = $rs[1];
    #say "$rs[0] $rs[1]";
  }
}
close MAP;

my $motelist = "motelist.txt";
system( "motelist -usb > $motelist" );
open MOTELIST,"<$motelist";
my %usbs ;
while (<MOTELIST>){
  chomp;
  my @rs = split /\s+/,$_;

  if (scalar @rs < 6){
    say $_;
    exit 1;
  }

  
  if ( $rs[5] =~ /ttyUSB/ ){
    my $port = (join '',($rs[5] =~ /\d+/g));
    my $phyId = $rs[4];
    $usbs{$phyId} = $port;
  }
}
close MOTELIST;

##
#say "ID PHYID PORT";
for my $k ( sort keys %index ){
  if ( defined $usbs{$index{$k}} ){
    say "$k $index{$k} $usbs{$index{$k}}";
  }
}
